package route

import (
	"fmt"
	"strconv"
	"strings"
)

type IpInfo struct {
	S1    string
	S2    string
	S3    string
	S4    string
	Check int
}

var ToIpNos []IpInfo

// 检查目的ip
func PraseToipNo(toIpNo string) {
	strs := strings.Split(toIpNo, ",")
	for i := 0; i < len(strs); i++ {
		ipToIpinfo(strs[i])
	}
}

// 127.0.0.1/24  to IpInfo
func ipToIpinfo(ip string) {
	strs := strings.Split(ip, "/")
	if len(strs) != 2 {
		fmt.Println("ip配置异常1:", ip)

	}
	strs1 := strings.Split(strs[0], ".")
	if len(strs1) != 4 {
		fmt.Println("ip配置异常2:", ip)
	}
	str := strs[1]
	if str != "8" && str != "16" && str != "24" && str != "32" {
		fmt.Println("ip配置异常3:", ip)
	}
	var info IpInfo
	info.S1 = strs1[0]
	info.S2 = strs1[1]
	info.S3 = strs1[2]
	info.S4 = strs1[3]

	i, err := strconv.Atoi(str)
	if err != nil {
		// 处理错误
		fmt.Println("ip配置异常4:", ip)
	}
	info.Check = i
	ToIpNos = append(ToIpNos, info)
}

// ip不禁止返回0 禁止返回1  addr 如127.0.0.1:80
func CheckAddr(addr string) int {
	var su = 0
	strs := strings.Split(addr, ":")
	for i := 0; i < len(ToIpNos); i++ {
		a := CheckIp(strs[0], ToIpNos[i])
		if a == 1 {
			return 1
		}
	}
	return su
}

// ip不禁止返回0 禁止返回1
func CheckIps(ip string) int {
	var su = 0
	for i := 0; i < len(ToIpNos); i++ {
		a := CheckIp(ip, ToIpNos[i])
		if a == 1 {
			return 1
		}
	}
	return su
}

// ip不禁止返回0 禁止返回1
func CheckIp(ip string, ipinfo IpInfo) int {
	var su = 0
	strs1 := strings.Split(ip, ".")
	if len(strs1) != 4 {
		//fmt.Println("ip配置异常2:", ip)
		return 0
	}

	if ipinfo.Check == 8 {
		if strs1[0] != ipinfo.S1 {
			return 0
		}
		return 1
	} else if ipinfo.Check == 16 {
		if strs1[0] != ipinfo.S1 {
			return 0
		}
		if strs1[1] != ipinfo.S2 {
			return 0
		}
		return 1
	} else if ipinfo.Check == 24 {
		if strs1[0] != ipinfo.S1 {
			return 0
		}
		if strs1[1] != ipinfo.S2 {
			return 0
		}
		if strs1[2] != ipinfo.S2 {
			return 0
		}
		return 1
	} else if ipinfo.Check == 32 {
		if strs1[0] != ipinfo.S1 {
			return 0
		}
		if strs1[1] != ipinfo.S2 {
			return 0
		}
		if strs1[2] != ipinfo.S3 {
			return 0
		}
		if strs1[3] != ipinfo.S4 {
			return 0
		}
		return 1
	}

	return su
}
